import { useState, useEffect, useCallback } from 'react'
import { View, Text } from '@tarojs/components'
import Card from '../component/card'
import Loading from '../component/load'
import Empty from '../component/empty'
import Taro, { setPageInfo, useTabItemTap, getCurrentInstance } from '@tarojs/taro'
import LgSelepicker from '../../components/selePick'
import { getStorage } from '../../components/utils/index'
import LgRefreshPage from '../../components/refreshPage'
import LgSearch from '../../components/searchInput'
import { LgSlide } from '../../components/slide'
import { HttpGet, HttpPost, HttpDelete, HttpPut } from '../../../network/servers'
import { getBaseUrl } from '../../../network/baseUrl'
import Utils from '../../../utils/index'
import _ from 'lodash'
import { getBrowserController } from '../../components/utils'
import { connect, useDispatch } from "react-redux";
import { Tabs, Popup } from 'antd-mobile'
import { LgPopLayer } from '../../components/popLayer'
import { LgTabs, LgTab } from '../../components/tabs'
import LgCheckbox from '../../components/checkbox'
import './index.scss'
import SearchPageComp from "../searchPageComp"

const storage = getStorage()
const {
  getNowToken,
  recentDateStr,
  replaceHost,
  useGetIsMapArray,
  getTimeAgo,
} = Utils

var wx = require('weixin-js-sdk')

const browserController = getBrowserController()
let InfoObj = {} as any
let weeklyRoutineId = '' // 记录当前选择的项的deleteID用于删除时传参
let isPopShow = 0 // 用来判断是否显示弹窗层 0不是 1是

function App(props) {

  const {
    userInfo,
    env,
    lg_ic,
    baseUrl,
    mainServer,
    systemInfo1,
    isAdvancedAdmin,
    isManage,
  } = props

  const { router } = getCurrentInstance();
  console.log(router.params)

  const [allCount, setAllCount] = useState(0)   //总数
  const [pullCount, setPullCount] = useState(1)
  const [newsList, setNewsList] = useState<any>([])
  const [totalPage, setTotalPage] = useState(0)
  const [loadVisible, setLoadVisible] = useState(true)
  const [keyword, setKeyword] = useState('')
  const [systemInfo, setSystemInfo] = useState(systemInfo1)

  const [currentStatus, setCurrentStatus] = useState('')
  const [currentType, setCurrentType] = useState('')
  const [isSearch, setIsSearch] = useState(false) //是否展示搜索框
  const [isOpen, setIsOpen] = useState(false) //是否筛选
  const [checkNum, setCheckNum] = useState(0);


  let UserType = storage.get('UserType') || userInfo.userType

  const getToken = () => {
    if (Utils.getQueryVariable('env') === 'weapp') {
      return Utils.getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || Utils.getQueryVariable('lg_tk')
    }
  }

  const getShowThisMsg = (item) => {  //获取当前待办在此环境是否展示
    if (Taro.getInWebview()) {  //小程序环境
      switch (String(item.receiverType)) {
        case '0':
        case '3':
        case '5':
          return true
        default:
          return false
      }
    } else {
      switch (String(item.receiverType)) {
        case '0':
        case '2':
        case '4':
        case '6':
          return true
        default:
          return false
      }
    }
  }

  const [typeList, setTypeList] = useState([])
  const [typeLength, setTypeLength] = useState(0)
  // 获取分类种类
  const getBasicInfo = () => {
    HttpGet({
      url: 'api/weekly/general/partition/list',
      data: {
        schoolId: storage.get('schoolId') || Utils.getQueryVariable('schoolId') || userInfo.schoolId,
        schoolLevel: storage.get('schoolLevel') || userInfo.schoolLevel
      }
    }).then((result) => {
      setTypeList(result.data)
      setCurrentType(result.data[0].partitionId)
      // window.nowCurrentType = result.data[0].partitionId
      console.log(result.data)
      if (result.data.length > 0) {
        let stringLength = 0
        result.data.forEach(i => {
          stringLength += i.partitionName.length
        })
        setTypeLength(stringLength)
        console.log(stringLength)
      } else {
        setTypeLength(0)
      }
    })
  }

  const [infoList, setInfoList] = useState([])
  // 获取周行事历管理列表
  const getNewsList = (n = 1, id) => {
    console.log(userInfo)
    console.log(n)
    HttpGet({
      url: `api/weekly/general/list/page`,
      data: {
        pageNum: 1,
        pageSize: n ? 8 * n : 8,
        keyword: keyword,
        // userId: userInfo.userId,
        partitionId: id ? id : window.nowCurrentType ? window.nowCurrentType : currentType,
        schoolId: storage.get('schoolId') || userInfo.schoolId,
      },
      load: true
    }).then((result) => {
      if (result.code == '200') {
        if (keyword == '') {
          closeSearch();
        }
        const info = result.data
        console.log(info)
        setInfoList(info)
        setNewsList(info)
        setTotalPage(Math.ceil(Number(result.total) / 8))
        setLoadVisible(false)
        setNewsList2([])
      }
    })
  }

  // 获取搜索中的新闻资讯列表
  const [newsList2, setNewsList2] = useState<any>([])

  const getNewsList2 = (value) => {

    console.log(userInfo)
    HttpGet({
      url: `api/weekly/general/list/page`,
      data: {
        pageNum: 1,
        pageSize: 8,
        keyword: value,
        // userId: userInfo.userId,
        partitionId: '',
        schoolId: storage.get('schoolId') || userInfo.schoolId,
      },
      load: true
    }).then((result) => {
      if (result.code == '200') {
        const info = result.data
        console.log(info)
        setNewsList2(info)
      }
    })
  }


  // 点击tabs
  const changeTabs = (key) => {
    // window.history.replaceState({},'',  `?lg_tk=${token}&isManage=1#/pages/newsInfoApp/index?partitionId=${key}`)
    setCurrentType(key)
    console.log(window.nowCurrentType)
    window.nowCurrentType = key
    console.log(window.nowCurrentType)
    getNewsList(1, key)
  }

  // ...按钮
  const [popupVisible, setPopupVisible] = useState(false)
  const changePopupVisible = (item) => {
    console.log(321312)
    isPopShow = 1
    setPopupVisible(!popupVisible)
    weeklyRoutineId = item.weeklyRoutineId
    console.log(item)
  }

  const jumpWeapp = (appId, path) => {
    try {
      browserController.navigateToMiniProgramForWebview(wx, {
        appId,//必传 跳转小程序唯一标识
        path,//必传 跳转后初始页面路径
        extraData: {},
        envVersion: 'release',//必传 跳转小程序的版本
      })
    } catch (err) {
      Taro.showToast({ title: err, icon: 'none' })
    }
  }

  //路由返回当前页面并刷新
  if (isManage === 1) {
    document.title = "周行事历管理"
    Taro.useDidShow(() => {
      setPullCount(1)
      setTimeout(() => {
        getNewsList(1, window.nowCurrentType)
        getBasicInfo()
      }, 200);
    })
  } else {
    document.title = "周行事历"
    Taro.useDidShow(() => {
      setPullCount(1)
      setTimeout(() => {
        getNewsList(1, window.nowCurrentType)
        getBasicInfo()
      }, 200);
    })
  }



  // 搜索变化
  const searchHandle = _.debounce((value) => {
    // setKeyword(value.trim())

    setH(value)
    getNewsList2(value)
  }, 500)

  //关闭搜索栏
  const closeSearch = _.debounce(() => {
    setIsSearch(false);
  }, 500)


  // 无限刷新
  const onPull = () => {
    if (totalPage > pullCount) {
      setPullCount(pullCount + 1)
      getNewsList(pullCount + 1, currentType)
    } else {
      Taro.showToast({
        title: '到底啦',
        icon: 'none'
      })
    }
  }
  // 下拉刷新
  const onDown = () => {
    getNewsList(pullCount, currentType)
    setTimeout(() => {
      Taro.showToast({
        title: '刷新成功'
      })
    }, 500)
  }

  useEffect(() => {
    // if ((UserType != '0' && isAdvancedAdmin == 0) && isManage === 0) {
    if (isManage === 0) {
      setCurrentStatus('1')
    }
    getNewsList(1, window.nowCurrentType ? window.nowCurrentType : currentType)
  }, [currentStatus, currentType, keyword, isAdvancedAdmin, checkNum])

  useEffect(() => {
    getBasicInfo()
  }, [])

  // 跳转发布页面
  const goCreate = (data) => {
    window.nowCurrentType = currentType
    let url = `/pages/newsInfoApp/createNews/index?weeklyRoutineId=0`
    Taro.navigateTo({
      url
    })
  }
  // 跳转编辑页面
  const goCreate2 = (e) => {
    e.stopPropagation()
    console.log(weeklyRoutineId)
    setPopupVisible(false)
    isPopShow = 0
    let url = '/pages/newsInfoApp/createNews/index'
    if (weeklyRoutineId) {
      url += '?weeklyRoutineId=' + weeklyRoutineId
    }
    Taro.navigateTo({
      url
    })
  }

  // 前往详情页
  const goDetail = (item) => {
    setPopupVisible(false)
    isPopShow = 0
    let url = '/pages/newsInfoApp/newsDetail/index'
    console.log(weeklyRoutineId)
    console.log(item)
    if (isManage == '1') {
      if (weeklyRoutineId) {
        url += '?weeklyRoutineId=' + weeklyRoutineId
        // url += '?id=' + data.newsId + ' &lg_tk=' + Utils.getQueryVariable('lg_tk') + '&lg_ic=' + Utils.getQueryVariable('lg_ic')
      }
      Taro.navigateTo({
        url
      })
    } else {
      url += '?weeklyRoutineId=' + item.weeklyRoutineId
      // url += '?id=' + data.newsId + ' &lg_tk=' + Utils.getQueryVariable('lg_tk') + '&lg_ic=' + Utils.getQueryVariable('lg_ic')
      Taro.navigateTo({
        url
      })
    }
  }

  // 前往分区设置页
  const goPartitionSetting = () => {
    setPopupVisible(false)
    isPopShow = 0
    let url = '/pages/newsInfoApp/partitionSetting/index'
    Taro.navigateTo({
      url
    })
  }

  const handleLayer = useCallback(() => {
    setIsOpen(!isOpen);
  }, [isOpen]);

  const handleCheck = useCallback((_checkNum) => {
    setCheckNum(_checkNum);
  }, []);

  const deleteWeeklyCase = () => {
    console.log(weeklyRoutineId)
    Taro.showModal({
      title: '提示',
      content: '确定要删除该周行事历吗?',
      success: function (res) {
        if (res.confirm) {
          HttpDelete({
            url: 'api/weekly/general/manage/del?weeklyRoutineId=' + weeklyRoutineId,
          }).then((result) => {
            getNewsList(pullCount, currentType)
            setPopupVisible(false)
            isPopShow = 0
            Taro.showToast({
              title: '删除成功',
              duration: 2000,
              mask: true
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
  return (
    <View className='todo_contanier'>
      <View className="todo_option">
        {/* 更新UI */}
        <View className='top_type'>
          {
            typeList.length > 0 ?
              <Tabs
                defaultActiveKey={currentType}
                activeKey={window.nowCurrentType ? window.nowCurrentType : currentType}
                onChange={(key) => { changeTabs(key) }}
              >
                {
                  typeList?.map((i, index) => {
                    return (
                      <Tabs.Tab title={i.partitionName} key={i.partitionId}>
                      </Tabs.Tab>
                    )
                  })
                }
              </Tabs> : ''
          }
        </View>
        {/* {
          isSearch ?
            <>
              <div className='gradient'></div>
              <View className='my_ipt2' style={{ width: isManage == '1' ? '480px' : '200px' }}>
                <LgSearch
                  value={keyword}
                  onConfirm={(value) => { setKeyword(value.trim()) }}
                  placeholder='请输入...'
                  onInput={searchHandle}
                />
                <SearchPageComp
                  setDataList={() => {
                    setNewsList2([])
                  }}
                  placeholder={'搜索部门通知标题'}
                  visible={isSearch}
                  dataList={newsList2}
                  loading={false}
                  childrenDom={childenDom()}
                  setVisible={() => {
                    setIsSearch(false)
                  }}
                  setWords={(h) => { searchHandle(h) }}></SearchPageComp>
              </View>
            </>
            :
            <>
              <div className='gradient'></div>
              {
                isManage == '1' ?
                  <View className='my_ipt' style={{ paddingRight: '15px' }}>
                    <View className='my_search_icon' onClick={() => setIsSearch(true)}></View>
                    <View className='my_screen_icon' onClick={() => goPartitionSetting()}></View>
                  </View> :
                  <View className='my_ipt' style={{ width: '64px' }}>
                    <View className='my_search_icon' style={{ borderRight: '0px' }} onClick={() => setIsSearch(true)}></View>
                  </View>
              }
            </>

        } */}

        <>
          {
            typeLength >= 12 ? <div className='gradient'></div> : ''
          }
          {
            isManage == '1' ?
              <View className='my_ipt' style={{ paddingRight: '15px' }}>
                <View className='my_search_icon' onClick={(e) => {
                  window.nowCurrentType = currentType
                  Taro.redirectTo({
                    url: `/pages/newsInfoApp/searchPageComp/index?lg_tk=${storage.get('token')}&isManage=1`
                  })
                  // setIsSearch(true)
                }}></View>
                <View className='my_screen_icon' onClick={() => goPartitionSetting()}></View>
              </View> :
              <View className='my_ipt' style={{ width: '64px' }}>
                <View className='my_search_icon' style={{ borderRight: '0px' }} onClick={() => {
                  window.nowCurrentType = currentType
                  Taro.redirectTo({
                    url: `/pages/newsInfoApp/searchPageComp/index`
                  })
                }}></View>
              </View>
          }
          {
            // isSearch ? 
            //   <SearchPageComp
            //   setDataList={() => {
            //     setNewsList2([])
            //   }}
            //   placeholder={'搜索部门通知标题'}
            //   visible={isSearch}
            //   dataList={newsList2}
            //   loading={false}
            //   childrenDom={childenDom()}
            //   setVisible={() => {
            //     setIsSearch(false)
            //   }}
            //   setWords={(h) => { searchHandle(h) }}>

            // </SearchPageComp>
            //  : ''
          }
        </>
      </View>
      <LgPopLayer
        position="bottom"
        isOpen={isOpen}
        showLayer={handleLayer}
        showClose
        title="排序筛选"
      >
        <View className="sort_view">
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 0}
              onClick={handleCheck.bind(null, 0)}
              children={'时间由近到远排序'}
            />
          </View>
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 1}
              onClick={handleCheck.bind(null, 1)}
              children={'时间由远到近排序'}
            />
          </View>
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 2}
              onClick={handleCheck.bind(null, 2)}
              children={'阅读次数升序排序'}
            />
          </View>
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 3}
              onClick={handleCheck.bind(null, 3)}
              children={'阅读次数降序排序'}
            />
          </View>
        </View>
      </LgPopLayer>

      <Loading mode="center" content="加载中..." isOpened={loadVisible}></Loading>
      <LgRefreshPage
        className='index'
        onPull={onPull}
        onDown={onDown}
        downText={['下拉刷新', '释放刷新']}
        pullText={['上拉加载更多', '释放加载更多']}>
        {
          infoList.length > 0 ?
            infoList.map((item, index) => {
              return (
                <div className='infoList' onClick={(e) => {
                  if (isManage == '1') {
                    if (isPopShow == 0) {
                      weeklyRoutineId = item.weeklyRoutineId
                      goCreate2(e)
                    }
                  } else {
                    goDetail(item)
                  }
                }}>
                  <div className='info_data1'>
                    <div className='info_title'>{item.title}</div>
                    {
                      isManage == '1' ? <div onClick={() => { changePopupVisible(item) }} className='option-btn'></div> : ''
                    }

                  </div>
                  <div className='info_data2'>
                    <div>时间：<span style={{ color: 'rgb(51,51,51)' }}>{`${item.startDate.slice(0, 10).replaceAll("-", "/")} - ${item.endDate.slice(0, 10).replaceAll("-", "/")
                      }`}</span></div>
                    <div>创建者：<span style={{ color: 'rgb(51,51,51)' }}>{item.userName}</span></div>
                  </div>
                </div>

              )
            })
            : !loadVisible ? <Empty /> : ''
        }
      </LgRefreshPage>
      <Popup
        visible={popupVisible}
        onMaskClick={() => {
          setPopupVisible(false)
          isPopShow = 0
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '29vh',
        }}
      >
        <div className='option_list'>
          <div className='option_item line' onClick={() => { goDetail() }}>查看详情</div>
          <div className='option_item line' onClick={(e) => goCreate2(e)}>编辑</div>
          <div className='option_item' onClick={() => { deleteWeeklyCase() }}>删除</div>
          <div className='split_line'></div>
          <div onClick={() => {
            setPopupVisible(false)
            isPopShow = 0
          }} className='option_item' style={{ color: '#ec5260' }}>取消</div>
        </div>
      </Popup>
      {/* 创建+ */}
      {
        isManage === 1 ?
          <><View className='create' onClick={() => goCreate('')}></View>
            <i className='create-shadow'></i></>
          : ''
      }

    </View>
  )
}


const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    baseUrl: commonData.baseUrl,
    mainServer: commonData.mainServer,
    lg_ic: commonData.lg_ic,
    systemInfo1: commonData.systemInfo,
    isAdvancedAdmin: commonData.advancedAdmin,
    isManage: commonData.isManage,
  }
}

export default connect(mainProps)(App)